package com.sse.redis.config;


import com.sse.constant.SseConstant;
import com.sse.redis.listener.SseMessagePushListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @title: MessageConfig
 * @Author xu-xiang
 * @Date: 2024/1/27 14:10
 * @description:
 */

@Configuration
public class MessageConfig {

    @Resource
    private SseMessagePushListener pushListener;

    /**
     * 配置 RedisMessageListenerContainer 监听器容器
     *
     * @param connectionFactory 连接工厂
     * @param listenerAdapter   消息侦听器适配器
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        // 消息主题列表
        List<Topic> topicList = new ArrayList<>();
        topicList.add(new ChannelTopic(SseConstant.SSE_MESSAGE_LISTENER_CHANNEL_TOPIC)); // 订阅主题
        // 订阅 通配符模式
        topicList.add(new PatternTopic(SseConstant.SSE_MESSAGE_LISTENER_PATTERN_TOPIC));

        // 将消息侦听器添加到容器中
        container.addMessageListener(listenerAdapter, topicList);
        return container;

    }

    /**
     * 消息侦听器适配器，能将消息委托给目标侦听器
     */
    @Bean
    public MessageListenerAdapter listenerAdapter() {
        return new MessageListenerAdapter(pushListener);
    }
}